package com.guli.gulimall.search.service;

import com.alibaba.fastjson.JSON;
import com.guli.common.utils.R;
import com.guli.common.vo.SkuEsModel;
import com.guli.gulimall.search.vo.*;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.Nested;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName SearchService
 * @Author Hao_YunKai
 * @Date 2022/1/8 9:54
 */
@Service
public class SearchService {
    @Autowired
    private RestHighLevelClient client;

    public R upAll(List<SkuEsModel> list) throws IOException {
        // 构建添加request
        BulkRequest request = new BulkRequest();
        for (SkuEsModel model : list) {
            request.add(new IndexRequest("product06a").id(model.getSkuId().toString())
                    .source(JSON.toJSONString(model),XContentType.JSON));
        }
        // 执行添加
        BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);

        // 有错误返回error
        if (bulkResponse.hasFailures()) {
            return R.error();
        }

        return R.ok();
    }

    //es查询
    public SearchResult search(SearchParam searchParam) throws Exception{
        // 一、构建查询请求
        SearchRequest searchRequest = new SearchRequest("product06a");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // keyword模糊查找
        if (StringUtils.isNotBlank(searchParam.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",searchParam.getKeyword()));
        }
        // 有库存
        if (BooleanUtils.isTrue(searchParam.isHasStock())) {
            boolQueryBuilder.must(QueryBuilders.termQuery("hasStock",searchParam.isHasStock()));
        }
        // 价格区间
        if (StringUtils.isNotBlank(searchParam.getSkuPrice())) {
            // 2000_8000 2000_ _8000
            String skuPrice = searchParam.getSkuPrice();
            if (skuPrice.startsWith("_")) {
                boolQueryBuilder.must(QueryBuilders.rangeQuery("skuPrice").lte(skuPrice.substring(1)));
            } else if (skuPrice.endsWith("_")) {
                boolQueryBuilder.must(QueryBuilders.rangeQuery("skuPrice").gte(skuPrice.substring(0,skuPrice.length() - 1)));
            } else {
                String[] s = skuPrice.split("_");
                boolQueryBuilder.must(QueryBuilders.rangeQuery("skuPrice").gte(s[0]).lte(s[1]));
            }
        }
        // 品牌brandId
        if (searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("brandId",searchParam.getBrandId()));
        }
        // 分类查询
        if (searchParam.getCatalog3Id() != null) {
            boolQueryBuilder.must(QueryBuilders.termQuery("catalogId",searchParam.getCatalog3Id()));
        }
        // 属性查找
        if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0) {
            for (String attr : searchParam.getAttrs()) {
                BoolQueryBuilder nestedBoolQueryBuilder = QueryBuilders.boolQuery();
                String[] s = attr.split("_");
                nestedBoolQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId",s[0]));
                nestedBoolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue",s[1].split(":")));
                boolQueryBuilder.must(QueryBuilders.nestedQuery("attrs",nestedBoolQueryBuilder, ScoreMode.None));
            }
        }
//        **********2.聚合构建*********
        // 2.1品牌聚合
        TermsAggregationBuilder brandAggregation = AggregationBuilders.terms("brandAgg").field("brandId");
        brandAggregation.subAggregation(AggregationBuilders.terms("brandNameAgg").field("brandName"));
        brandAggregation.subAggregation(AggregationBuilders.terms("brandImgAgg").field("brandImg"));
        searchSourceBuilder.aggregation(brandAggregation);
        // 2.2分类聚合
        TermsAggregationBuilder catalogAggregation = AggregationBuilders.terms("catalogIdAgg").field("catalogId");
        catalogAggregation.subAggregation(AggregationBuilders.terms("catalogNameAgg").field("catalogName"));
        searchSourceBuilder.aggregation(catalogAggregation);
        //2.3 属性聚合
        NestedAggregationBuilder nested = AggregationBuilders.nested("attrAgg", "attrs");
        // 构建attrId属性子聚合
        TermsAggregationBuilder attrIdAggregation = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId");
        attrIdAggregation.subAggregation(AggregationBuilders.terms("attrNameAgg").field("attrs.attrName"));
        attrIdAggregation.subAggregation(AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue"));
        nested.subAggregation(attrIdAggregation);
        searchSourceBuilder.aggregation(nested);

        // 分页
        searchSourceBuilder.from((searchParam.getPageNum() - 1) * searchParam.getPageSize());
        searchSourceBuilder.size(searchParam.getPageSize());
        // 高亮
        searchSourceBuilder.highlighter(new HighlightBuilder().field("skuTitle").preTags("<span style='color:red'>").postTags("</span>"));

        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);

        // 二、执行查询
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
//        三、处理结果
        SearchHits hits = searchResponse.getHits();
        TotalHits totalHits = hits.getTotalHits();
        // the total number of hits, must be interpreted in the context of totalHits.relation
        long numHits = totalHits.value;
        // whether the number of hits is accurate (EQUAL_TO) or a lower bound of the total (GREATER_THAN_OR_EQUAL_TO)
        TotalHits.Relation relation = totalHits.relation;
        float maxScore = hits.getMaxScore();
        // 遍历结果集
        SearchHit[] searchHits = hits.getHits();

        ArrayList<SkuEsModel> products = new ArrayList<>();

        for (SearchHit hit : searchHits) {
            // do something with the SearchHit
            String index = hit.getIndex();
            String id = hit.getId();
            float score = hit.getScore();
            String sourceAsString = hit.getSourceAsString();
            SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
            // 赋值主键
            skuEsModel.setSkuId(Long.parseLong(id));
            // 处理高亮
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlight = highlightFields.get("skuTitle");
            if (highlight != null) {
                Text[] fragments = highlight.fragments();
                String fragmentString = fragments[0].string();
                skuEsModel.setSkuTitle(fragmentString);
            }
            products.add(skuEsModel);
        }

//      3 ================处理聚合=================
        Aggregations aggregations = searchResponse.getAggregations();
        // 3.1品牌聚合
        ArrayList<BrandVo> brandVos = new ArrayList<>();
        // 构建是什么类型 就用什么类型接收
        Terms brandIdAgg = aggregations.get("brandAgg");
        for (Terms.Bucket bucket : brandIdAgg.getBuckets()) {
            BrandVo brandVo = new BrandVo();
            brandVo.setBrandId(bucket.getKeyAsNumber().longValue());
            Aggregations bucketAggregations = bucket.getAggregations();
            // 3.1.1 品牌名称
            Terms brandNameAgg = bucketAggregations.get("brandNameAgg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            // 3.1.2 品牌图片
            Terms brandImgAgg = bucketAggregations.get("brandImgAgg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);

            brandVos.add(brandVo);
        }

        //3.2 分类聚合
        ArrayList<CatalogVo> catalogVos = new ArrayList<>();
        Terms catalogIdAggregation = aggregations.get("catalogIdAgg");
        for (Terms.Bucket bucket : catalogIdAggregation.getBuckets()) {
            CatalogVo catalogVo = new CatalogVo();
            catalogVo.setCatalogId(bucket.getKeyAsNumber().longValue());
            // 3.2.1 分类名称
            Aggregations catalogNameAggregations = bucket.getAggregations();
            Terms catalogNameAgg = catalogNameAggregations.get("catalogNameAgg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);

            catalogVos.add(catalogVo);
        }

        //3.3 属性聚合
        ArrayList<AttrVo> attrVos = new ArrayList<>();
        Nested attrAgg = aggregations.get("attrAgg");
        Aggregations nestedSubAggregations = attrAgg.getAggregations();
        // attrId聚合
        Terms attrIdAgg = nestedSubAggregations.get("attrIdAgg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            AttrVo attrVo = new AttrVo();
            attrVo.setAttrId(bucket.getKeyAsNumber().longValue());
            // 3.3.1 子聚合
            Aggregations bucketAggregations = bucket.getAggregations();
            // 3.3.1.1 属性名
            Terms attrNameAgg = bucketAggregations.get("attrNameAgg");
            attrVo.setAttrName(attrNameAgg.getBuckets().get(0).getKeyAsString());
            // 3.3.1.2 属性值
            Terms attrValueAgg = bucketAggregations.get("attrValueAgg");
            ArrayList<String> attrValues = new ArrayList<>();
            for (Terms.Bucket attrValueAggBucket : attrValueAgg.getBuckets()) {
                // 收集所有value
                attrValues.add(attrValueAggBucket.getKeyAsString());
            }
            attrVo.setAttrValue(attrValues);

            attrVos.add(attrVo);
        }

        SearchResult searchResult = new SearchResult();
        searchResult.setProducts(products);
        searchResult.setBrands(brandVos);
        searchResult.setCatalogs(catalogVos);
        searchResult.setAttrs(attrVos);
        searchResult.setTotal(numHits);  //总记录数
        // 总页数
        Integer size = searchParam.getPageSize();
        int totalPage = (int) (numHits % size == 0 ? numHits / size : (numHits / size + 1));
        searchResult.setTotalPage(totalPage);
        // 页数导航页
        ArrayList<Integer> paNav = new ArrayList<>();
        for (int i = 1; i <= totalPage; i++) {
            paNav.add(i);
        }
        searchResult.setPaNav(paNav);
        searchResult.setPageNum(searchParam.getPageNum());
        return searchResult;
    }
}
